package xj.graph2d.app;

import static xj.app.BaseApplicationFrame.getResourceString;
import static xj.app.BaseApplicationFrame.hideSplashScreen;
import static xj.app.BaseApplicationFrame.logInfo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JOptionPane;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

import xj.graph2d.app.project.Project;
import xj.graph2d.app.project.ProjectManager;
import xj.lang.CodeWriter;
import xj.util.xml.ErrorMessageHandler;
import xj.util.xml.XMLUtil;

public class UserProfile { 
  
  public UserProfile(DrawApp main) { 
    this.main = main;
    
  }

  public List<String> getInitProjects() { 
    return initProjects;
  }

  public String getCurrentProject() { 
    return currentProject; 
  }

  public void processUserConfig() {
    if (debug) {
      System.out.println("DrawApp.processUserConfig()");
    }

    /*
     * user.name User's account name user.home User's home directory
     * user.dir User's current working directory
     */

    String userHome = System.getProperty("user.home");
    if (userHome == null) {
      userHome = System.getProperty("user.dir");
    }
    String userConfDir;
    if (userHome != null) {
      userConfDir = (userHome + File.separator + main.getAppDir() + 
		     File.separator + userConfigDir);
    } else {
      userConfDir = userConfigDir;
    }

    if (debug) {
      System.out.println("DrawApp.processUserConfig() userConfDir=" + userConfDir);
    }
    logInfo("UserConfig: userConfDir=" + userConfDir);

    File confd = new File(userConfDir);
    if (!confd.exists()) {
      logInfo("UserConfig: userConfDir does not exist, attempt to create");
      // confd.mkdir();
      Project.createDir(confd);      
    }
    if (confd.isDirectory()) {
      logInfo("UserConfig: userConfDir exists");
      String confname = (userConfDir + File.separator + userConfigFile);
      File conf = new File(confname);
      if (conf.exists()) {
	logInfo("UserConfig: user config file " + confname + " exists");
	try {
	  InputStream confin = null;
	  confin = new FileInputStream(conf);
	  org.w3c.dom.Document doc = null;
	  if (confin != null) {
	    ErrorMessageHandler errorHandler = new ErrorMessageHandler(confname);
	    doc = XMLUtil.parseXMLDocument(confin, errorHandler, false);
	    if (errorHandler.hasErrorOrWarning()) {

	    }

	    if (doc != null) {
	      Element docElement = doc.getDocumentElement();
	      XMLUtil.stripWhiteSpace(docElement);

	      if ("UserConfig".equals(docElement.getLocalName())) {
		if (docElement.hasChildNodes()) {
		  NodeList nodes = docElement.getChildNodes();
		  if (nodes != null) {
		    int n = nodes.getLength();
		    for (int i = 0; i < n; i++) {
		      Node node = nodes.item(i);
		      if (node.getNodeType() == Node.ELEMENT_NODE) {
			Element e = (Element) node;
			String name = e.getLocalName();
			if ("ProjectManager".equals(name)) {
			  String curproj = e.getAttribute("current");			 
			  if (e.hasChildNodes()) {
			    initProjects = new ArrayList<String>();
			    NodeList pnodes = e.getChildNodes();
			    if (pnodes != null) {
			      int m = pnodes.getLength();
			      for (int j = 0; j < m; j++) {
				Node pnode = pnodes.item(j);
				if (pnode.getNodeType() == Node.ELEMENT_NODE) {
				  Element p = (Element) pnode;
				  String pname = p.getLocalName();
				  if ("Project".equals(pname)) {
				    String path = p.getAttribute("path");
				    initProjects.add(path);
				  }
				}
			      }
			    }			    
			  }
			  if (curproj != null && 
			      curproj.length() > 0) { 
			    currentProject = curproj;
			  }

			  // } else if () {
			}
		      }
		    }
		  }
		}
	      }
	    }
	  }

	} catch (IOException e) {
	  System.err.println("Error reading file " + confname + ": " + e.getMessage());
	  logInfo("UserConfig: Error reading file " + confname + ": " + e.getMessage());
	  if (debug) {
	    e.printStackTrace(System.err);
	  }
	} catch (SAXParseException e) {
	  // error in input
	  System.err.println("Error " + confname + ":" + e.getMessage());
	  logInfo("UserConfig: Error " + confname + ":" + e.getMessage());
	  if (debug) {
	    e.printStackTrace(System.err);
	  }
	} catch (SAXException e) {
	  // error in input
	  System.err.println("Error " + confname + ":" + e.getMessage());
	  logInfo("UserConfig: Error " + confname + ":" + e.getMessage());
	  if (debug) {
	    e.printStackTrace(System.err);
	  }
	}

      } else {
	if (debug) {
	  System.out.println("DrawApp.processUserConfig() no user onfig file");
	}
	logInfo("UserConfig: no user config file");

	
      }
    }

  }

  public void saveUserConfig() {
    String userHome = System.getProperty("user.home");
    if (userHome == null) {
      userHome = System.getProperty("user.dir");
    }
    String userConfDir;
    if (userHome != null) {
      userConfDir = (userHome + File.separator + main.getAppDir() + 
		     File.separator + userConfigDir);
    } else {
      userConfDir = userConfigDir;
    }
    File confd = new File(userConfDir);
    if (!confd.exists()) {
      confd.mkdirs();
    }
    if (confd.isDirectory()) {
      String confname = (userConfDir + File.separator + userConfigFile);
      File conf = new File(confname);

      try {
	PrintWriter cout = new PrintWriter(new BufferedWriter(new FileWriter(conf)));
	CodeWriter out = new CodeWriter(cout);
	out.setIndentSize(1);
	String appName = main.getAppName();
	String namespaceURI = main.getNamespaceURI();
	String namespacePrefix = main.getNamespacePrefix();
	boolean useDefaultNamespace = true;

	out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>");
	if (appName != null) {
	  out.println("<!-- Created by " + appName + " " + (new Date()) + " -->");
	}
	String rootname = Project.getPrefixedName("UserConfig",
						  useDefaultNamespace ? null : namespacePrefix);

	out.print("<" + rootname);
	if (namespaceURI != null && namespaceURI.length() > 0) {
	  out.print(" xmlns");
	  if (!useDefaultNamespace && namespacePrefix != null && 
	      namespacePrefix.length() > 0) {
	    out.print(":" + namespacePrefix);
	  }
	  out.print("=\"" + namespaceURI + "\"");
	}
	out.println(">");
	out.thisIndentInc();

	ProjectManager projectManager = main.getProjectManager();
	if (projectManager != null) {
	  projectManager.save(out);
	}

	out.thisIndentDec();
	out.println("</" + rootname + ">");
	out.close();
      } catch (IOException e) {
	System.err.println("Error writing file " + confname + ": " + e.getMessage());
	if (debug) {
	  e.printStackTrace(System.err);
	}
      }
    }
  }

  protected DrawApp main;

  protected static String userConfigDir = ".avm";

  protected static String userConfigFile = "config.xml";

  protected List<String> initProjects = null;
  
  protected String currentProject = null; 

  public static final boolean debug = false;

}
